﻿using Microsoft.Extensions.FileProviders;
using System;
using System.IO;

namespace Orchid.Blazor.Hosting.Repositories
{
    /// <summary>
    /// 网站重写文件。
    /// </summary>
    public class WebRewriteFile : MarshalByRefObject, IFileInfo
    {
        private IFileInfo _file;
        private Func<Stream, Stream> _rewriteHandler;

        /// <summary>
        /// 名称。
        /// </summary>
        public string Name => _file.Name;
        /// <summary>
        /// 是否目录。
        /// </summary>
        public bool IsDirectory => _file.IsDirectory;
        /// <summary>
        /// 物理路径。
        /// </summary>
        public string PhysicalPath { get; }
        /// <summary>
        /// 是否存在。
        /// </summary>
        public bool Exists => _file.Exists;
        /// <summary>
        /// 大小。
        /// </summary>
        public long Length => _file.Length;
        /// <summary>
        /// 最后更改时间。
        /// </summary>
        public DateTimeOffset LastModified => _file.LastModified;

        /// <summary>
        /// <inheritdoc cref="WebRewriteFile"/>
        /// </summary>
        /// <param name="file">文件。</param>
        /// <param name="rewriteHandler">重写操作器。</param>
        public WebRewriteFile(IFileInfo file, Func<Stream, Stream> rewriteHandler)
        {
            _file = file ?? throw new ArgumentNullException(nameof(file));
            _rewriteHandler = rewriteHandler ?? throw new ArgumentNullException(nameof(rewriteHandler));
        }

        public Stream CreateReadStream()
        {
            var stream = _file.CreateReadStream();
            if (stream == null) return stream;
            return _rewriteHandler.Invoke(stream);
        }
    }
}
